package com.arthur.budget;

import java.util.LinkedList;

import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;

public class BudgetManager {
    static BudgetManager self;
    static Context sCtx;
    
    static final String TOTAL = "total";
    static final int TOAST_TIME = 10;
    
    LinkedList<Float> inputCache;
    SharedPreferences money;
    
    public static BudgetManager getInstance(Context ctx) {
        sCtx = ctx;
        
        if (self == null) {
            self = new BudgetManager();
        }
        
        return self;
    }
    
    public BudgetManager() {
        money = sCtx.getSharedPreferences("MONEY", 0);
        inputCache = new LinkedList<Float>();
    }
    
    public void setTotal(float newTotal) {
        SharedPreferences.Editor totalEditor = money.edit();
        totalEditor.putFloat(TOTAL, newTotal);
        totalEditor.commit();
    }
    
    public float getTotal() {
        return money.getFloat(TOTAL, 0);
    }
    
    public void spend(float spent) {
        inputCache.push(spent);
        float total = money.getFloat(TOTAL, 0);
        
        total -= spent;
        setTotal(total);
        
        Toast toast = Toast.makeText(sCtx, "Spent [" + spent + "]", TOAST_TIME);
        toast.show();
    }
    
    public void undo() {
        Float undoAmount = inputCache.poll();
        
        if (undoAmount != null) {
            float total = money.getFloat(TOTAL, 0);
            
            total += undoAmount;
            setTotal(total);
            
            Toast toast = Toast.makeText(sCtx, "Undo [" + undoAmount + "]", TOAST_TIME);
            toast.show();
        } else {
            Toast toast = Toast.makeText(sCtx, "No more undo left", TOAST_TIME);
            toast.show();
        }
    }
}
